package com.miracle9.game.util;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import javax.crypto.Cipher;

public class MyRsa {

    public static void main(String[] args) throws UnsupportedEncodingException {
        String encode = MyEncode.encode(MyRsa.getMyRsaInstance().cipherRSA());
        System.out.println(encode);
        byte[] decodedUsername = MyRsa.getMyRsaInstance().cipherRSA(MyEncode.decode(encode));
        System.out.println(new String(decodedUsername));
    }

    private static String bw = "mSs9e2zYPFDs8nuNl8safQ1pNvhskGg2opu7AHmPoGODnp6jFoI4C0tXa4KQMUg1SjOPVipP4grEl6q8G+QwQIrLpVo1n6tnK09GCWsUyTjG/Y75totuRxx+fWpVH0eWNdgO7ZGAk0H1b0kCH4ENUUW51z+d+Xt5A53xkRzyCSU=";
    private static String bx = "AQAB";
    private static String by = "SbownAqmg1II3Cdw3pIbK/qanKUzzMb9FYSUnQPmiLOeFWoS4rDHvVgEunFcavxw+kibRESVsx6vxrmeVmaeepQeJ7lqj1GJSbRAOoOLaI1KEY0QzsjNTlY1peKa/ZQ8+dNs1D+fD4O7uWmJxzEZetWYrzEo36EEDX8x3a9uZAE=";
    public PublicKey bz;
    public PrivateKey bA;
    private static MyRsa bB;

    public static MyRsa getMyRsaInstance() {
        if (bB == null) {
            bB = new MyRsa();
            bB.init();
        }
        return bB;
    }

    public void init() {
        byte[] modulusBytes = MyEncode.decode(bw);
        byte[] exponentBytes = MyEncode.decode(bx);
        BigInteger modulus = new BigInteger(1, modulusBytes);
        BigInteger exponent = new BigInteger(1, exponentBytes);

        RSAPublicKeySpec rsaPubKey = new RSAPublicKeySpec(modulus, exponent);
        KeyFactory fact = null;
        try {
            fact = KeyFactory.getInstance("RSA");
            this.bz = fact.generatePublic(rsaPubKey);
        } catch (Exception e) {
            e.printStackTrace();
        }
        byte[] expBytes = MyEncode.decode(by);
        BigInteger privatExponent = new BigInteger(1, expBytes);

        RSAPrivateKeySpec privSpec = new RSAPrivateKeySpec(modulus, privatExponent);
        try {
            this.bA = fact.generatePrivate(privSpec);
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        }
    }

    public byte[] cipherRSA() {
        try {
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(1, this.bz);

            return cipher.doFinal("admin".getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public byte[] cipherRSA(byte[] encrypted) {
        try {
            Cipher cipher = Cipher.getInstance("RSA");

            cipher.init(2, this.bA);
            return cipher.doFinal(encrypted);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
